// pages/booking/index.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  data: {
    storeName: '', // 门店名称
    bookingList: [],
    activeStatus: 'all', // 当前激活的状态
    loading: false,
    isLoggedIn: false,
    page: 1,
    pageSize: 10,
    hasMore: true,
    bookingId: null // 添加bookingId来存储URL中传递的预约ID
  },

  onLoad: function (options) {
    // TODO: 从全局变量或缓存中获取当前门店信息
    this.setData({
      storeName: wx.getStorageSync('currentStoreName') || '门店订单'
    });
  },

  /**
   * 用户点击选择门店
   */
  selectStore: function() {
    wx.reLaunch({
      url: '/pages/index/index',
      fail: (e) => {
        console.error(e);
      }
    });
  },



  onShow: function () {
    // 只在登录状态发生变化时重新检查
    const app = getApp();
    const isLoggedIn = app.globalData.isLoggedIn;
    
    if (isLoggedIn !== this.data.isLoggedIn) {
      this.setData({
        isLoggedIn: isLoggedIn
      });
      
      if (isLoggedIn) {
        this.resetAndLoadBookingList();
      } else {
        this.setData({
          bookingList: [],
          loading: false
        });
      }
    }
  },

  /**
   * 切换订单状态Tab
   */
  onStatusTabChange: function(e) {
    const status = e.currentTarget.dataset.status;
    if (status === this.data.activeStatus) {
      return;
    }
    this.setData({
      activeStatus: status,
    });
    this.resetAndLoadBookingList();
  },

  // 重置并加载预约列表
  resetAndLoadBookingList: function () {
    this.setData({
      page: 1,
      bookingList: [],
      hasMore: true
    });
    this.loadBookingList();
  },

  // 加载预约列表
  loadBookingList: function () {
    if (!this.data.hasMore) return;
    this.setData({ loading: true });
    
    // 计算30天前的时间戳
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const startTime = Math.floor(thirtyDaysAgo.getTime() / 1000);

    // 构建请求参数
    const params = {
      page: this.data.page,
      page_size: this.data.pageSize,
      store_id: wx.getStorageSync('currentStoreId') || '',
      start_time: startTime // 添加开始时间参数
    };

    // 处理订单状态参数
    if (this.data.activeStatus && this.data.activeStatus !== 'all') {
      params.status = this.data.activeStatus;
    }

    // 调用API获取预约列表
    api.order.getMyBookings(params)
      .then(res => {
        if (res.success) {
          const newList = res.data.list || [];
          const formattedList = newList.map(item => {
            // 格式化时间和日期
            const startTime = item.start_time ? new Date(item.start_time * 1000) : null;
            const endTime = item.end_time ? new Date(item.end_time * 1000) : null;
            
            let date = '';
            let time = '';
            
            if (startTime) {
              date = utils.formatDate(startTime);
              time = `${utils.formatTime(startTime)} - ${endTime ? utils.formatTime(endTime) : ''}`;
            }
            
            return {
              ...item,
              id: item.id,
              date: date,
              time: time,
              status: item.status,
              total_amount: item.total_amount || 0,
              createTime: utils.formatTimestampWithTime(item.created_at || item.create_time)
            };
          });

          // 更新数据
          this.setData({
            bookingList: [...this.data.bookingList, ...formattedList],
            page: this.data.page + 1,
            hasMore: newList.length >= this.data.pageSize,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.message || '获取预约列表失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('获取预约列表失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 查看预约详情
  onTapBookingDetail: function (e) {
    const bookingId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/booking/detail?id=${bookingId}`
    });
  },

  // 确认到店
  onConfirmArrival: function (e) {
    const bookingId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定用户已到店吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '确认中...'
          });

          api.order.updateStatus({ id: bookingId, status: 2 }) // 2: 已确认
            .then(res => {
              wx.hideLoading();
              if (res.success) {
                wx.showToast({
                  title: '确认成功',
                  icon: 'success'
                });
                this.resetAndLoadBookingList();
              } else {
                wx.showToast({
                  title: res.message || '确认失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              wx.hideLoading();
              console.error('确认到店失败:', err);
              wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 取消预约
  onTapCancelBooking: function (e) {
    const bookingId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消该预约吗？',
      success: (res) => {
        if (res.confirm) {
          // 显示加载中
          wx.showLoading({
            title: '取消中...'
          });

          // 调用API取消预约
          api.order.cancelBooking(bookingId)
            .then(res => {
              wx.hideLoading();

              if (res.success) {
                wx.showToast({
                  title: '取消成功',
                  icon: 'success'
                });

                // 重新加载预约列表
                this.resetAndLoadBookingList();
              } else {
                wx.showToast({
                  title: res.message || '取消失败',
                  icon: 'none'
                });
              }
            })
            .catch(err => {
              wx.hideLoading();
              console.error('取消预约失败:', err);
              wx.showToast({
                title: '网络错误，请稍后再试',
                icon: 'none'
              });
            });
        }
      }
    });
  },

  // 前往登录
  onTapLogin: function () {
    wx.navigateTo({
      url: '/pages/user/login'
    });
  },

  // 前往场馆列表
  onTapToVenueList: function (e) {
    console.log("onTapToVenueList:",e);
    wx.switchTab({
      url: '/pages/venue/room',
      complete:(res)=>{
        console.log("onTapToVenueList complete:", res)
      }
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.resetAndLoadBookingList().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom: function () {
    if (this.data.hasMore && !this.data.loading) {
      this.loadBookingList();
    }
  },

  // 根据ID加载特定的预约订单
  loadBookingById: function(id) {
    wx.showLoading({ title: '加载订单详情...' });
    
    api.order.getBookingDetail(id)
      .then(res => {
        wx.hideLoading();
        if (res.success && res.data) {
          // 订单加载成功，跳转到详情页
          wx.navigateTo({
            url: `/pages/booking/detail?id=${id}`
          });
        } else {
          wx.showToast({
            title: '未找到订单信息',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('加载订单详情失败:', err);
        wx.showToast({
          title: '获取订单失败，请稍后再试',
          icon: 'none'
        });
      });
  },

  // 选择订单状态
  selectStatus: function (e) {
    const status = e.currentTarget.dataset.status;
    let statusText = '全部';
    
    // 更新状态文本
    switch (status) {
      case '1':
        statusText = '待确认';
        break;
      case '2':
        statusText = '已确认';
        break;
      case '3':
        statusText = '已完成';
        break;
      case '4':
        statusText = '已取消';
        break;
    }
    
    this.setData({
      selectedStatus: status,
      statusText: statusText,
      showStatusDropdown: false
    });
    
    this.resetAndLoadBookingList();
  },

  // 选择订单类型
  selectOrder: function (e) {
    const type = e.currentTarget.dataset.type;
    let orderText = '全部订单';
    
    // 更新订单类型文本
    switch (type) {
      case '0':
        orderText = '棋牌订单';
        break;
      case '1':
        orderText = '台球订单';
        break;
    }
    
    this.setData({
      selectedOrderType: type,
      orderText: orderText,
      showOrderDropdown: false
    });
    
    this.resetAndLoadBookingList();
  },

  // 跳转到历史订单
  onTapHistoryOrders: function () {
    wx.navigateTo({
      url: '/pages/booking/history'
    });
  }
});